package com.faithbj.freemarker;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class DataMapUtil {
    
    private static Map<String, Object> dataMap = new HashMap<String, Object>();
       
    /**
     * 将对象转换成Map
     * @param obj 对象类
     * @return
     */
    public static Map<String,Object> setObjToMap(Object obj){
        Class<?> c;
        try {
            c = Class.forName(obj.getClass().getName());
            Method[] methods = c.getMethods();
            for(Method method:methods){
                String methodName = method.getName();
                if(methodName.startsWith("get")){
                    Object value = method.invoke(obj);
                    if(value != null){
                        if(value.getClass().getClassLoader() != null){  //处理自定义的对象类型
                            setObjToMap(value);
                        }
                        String key = methodName.substring(3);
                        key = key.substring(0, 1).toLowerCase() + key.substring(1);
//                        if("java.util.Date".equals(value.getClass().getName())){
//                            value = "hello";
//                        }
                        dataMap.put(key, value);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataMap;
    }
}
